package com.tencreat.service.mall.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.domain.mall.MallConsult;
import com.tencreat.domain.mall.dto.PraiseAddDTO;
import com.tencreat.service.mall.IMallConsultService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.tencreat.mapper.mall.MallPraiseMapper;
import com.tencreat.domain.mall.MallPraise;
import com.tencreat.service.mall.IMallPraiseService;

/**
 * 点赞记录Service业务层处理
 *
 * @author tencreat
 * @company: 深圳腾创互联科技有限公司
 * @link: https://tencreat.com
 * @date 2022-12-29
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class MallPraiseServiceImpl extends ServiceImpl<MallPraiseMapper, MallPraise> implements IMallPraiseService {

    @Autowired
    private IMallConsultService mallConsultService;

    /**
     * 分页查询
     * @param iPage 分页参数
     * @param mallPraise 查询条件
     * @return 分页结果
     */
    @Override
    public IPage<MallPraise> page(IPage<MallPraise> iPage, MallPraise mallPraise) {
        return baseMapper.page(iPage, mallPraise);
    }

    @Override
    public void save(PraiseAddDTO dto){
        Long uuid = SecurityUtils.getLoginUser().getAccountLogin().getUuid();
        MallPraise praise = new MallPraise();
        praise.setUserId(uuid);
        praise.setValueId(dto.getValueId());
        praise.setType(dto.getType());
        try {
            baseMapper.insert(praise);
            // 加点赞数
            if (dto.getType() == 0) {
                MallConsult one = mallConsultService.lambdaQuery().eq(MallConsult::getId, dto.getValueId()).one();
                if (one != null) {
                    mallConsultService.lambdaUpdate().set(MallConsult::getLikesCount,one.getLikesCount()+1)
                            .eq(MallConsult::getId,one.getId())
                            .update();
                }
            }
        } catch (Exception e) {
            baseMapper.deletePraise(praise);
            // 减点赞数
            if (dto.getType() == 0) {
                MallConsult one = mallConsultService.lambdaQuery().eq(MallConsult::getId, dto.getValueId()).one();
                if (one != null) {
                    mallConsultService.lambdaUpdate().set(MallConsult::getLikesCount,one.getLikesCount()-1)
                            .eq(MallConsult::getId,one.getId())
                            .update();
                }
            }
        }
    }
}
